#!/usr/bin/env bash

RETURN=0
CLANG_FORMAT=$(which clang-format)
if [ $? -ne 0 ]; then
    echo "[!] clang-format not installed. Unable to check source file format policy." >&2
    exit 1
fi

DIFF=$(which colordiff)
if [ $? -ne 0 ]; then
    DIFF=diff
fi

FILES=`git diff --cached --name-only --diff-filter=ACMR | grep -E "\.(c|cpp|h)$"`
for FILE in $FILES; do
    nf=`git checkout-index --temp $FILE | cut -f 1`
    tempdir=`mktemp -d` || exit 1
    newfile=`mktemp ${tempdir}/${nf}.XXXXXX` || exit 1
    basename=`basename $FILE`

    source="${tempdir}/${basename}"
    mv $nf $source
    cp .clang-format $tempdir
    $CLANG_FORMAT $source > $newfile 2>> /dev/null
    $DIFF -u -p -B --label="modified $FILE" --label="expected coding style" \
          "${source}" "${newfile}"
    r=$?
    rm -rf "${tempdir}"
    if [ $r != 0 ] ; then
        echo "[!] $FILE does not follow the consistent coding style." >&2
        RETURN=1
    fi
    if [ $RETURN -eq 1 ]; then
        echo "" >&2
        echo "Make sure you indent as the following:" >&2
        echo "    clang-format -i $FILE" >&2
        echo
    fi
done

echo "Following files need to be cleaned up:"
echo "${FILES[*]}"

if [ $RETURN -eq 1 ]; then
    # Ask the question (not using "read -p" as it uses stderr not stdout)
    echo -en "ignore and commit ? [y/n]"

    # Read the answer
    if tty >/dev/null 2>&1; then
        TTY=$(tty)
    else
        TTY=/dev/tty
    fi
    read REPLY < "$TTY"

    # Check if the reply is valid
    case "$REPLY" in
        N*|n*) exit 1 ;;
        Y*|y*) exit 0 ;;
    esac
fi